#include "Mesh.h"
#include <direct.h> // for getcwd
#include <sys/stat.h> 
#include <stdlib.h>// for MAX_PATH
//#include <atlbase.h>

Mesh::Mesh(){
	
}

Mesh::Mesh(string name, string location){
	mName = name;
	mLocation = location;
	mNumMaterials = 0;
}

void Mesh::LoadMesh(LPDIRECT3DDEVICE9 d3ddev){

//  struct stat stFileInfo;
//  int intStat;
//
//char *path=NULL;
//size_t size;
//path=getcwd(path,_MAX_PATH);
//
//  // Attempt to get the file attributes
//  intStat = stat(mLocation.c_str(),&stFileInfo); 
//  if(intStat  ==0){
//		mNumMaterials = 0;
//  }
//  else{
//mNumMaterials = 0;
//  }

LPD3DXBUFFER mBufMaterial;

D3DXLoadMeshFromX(mLocation.c_str(),    // load this file
				  D3DXMESH_SYSTEMMEM,    // load the mesh into system memory
				  d3ddev,    // the Direct3D Device
				  NULL,    // we aren't using adjacency
				  &mBufMaterial,    // put the materials here
				  NULL,    // we aren't using effect instances
				  &mNumMaterials,    // the number of materials in this model
				  &mMesh);    // put the mesh here

// a pointer to a material buffer

// retrieve the pointer to the buffer containing the material information
D3DXMATERIAL* tempMaterials = (D3DXMATERIAL*)mBufMaterial->GetBufferPointer();

// create a new material buffer for each material in the mesh
mMaterials = new D3DMATERIAL9[mNumMaterials];
mTextures = new LPDIRECT3DTEXTURE9[mNumMaterials];

for(DWORD i = 0; i < mNumMaterials; i++)    // for each material...
{
	mMaterials[i] = tempMaterials[i].MatD3D;    // get the material info...
	mMaterials[i].Ambient = mMaterials[i].Diffuse;    // and make ambient the same as diffuse
	
//USES_CONVERSION;    // allows certain string conversions
	// if there is a texture to load, load it
	if(FAILED(D3DXCreateTextureFromFile(d3ddev,
										tempMaterials[i].pTextureFilename,
										&mTextures[i])))
		mTextures[i] = NULL;    // if there is no texture, set the texture to NULL
}

}

void Mesh::Draw(LPDIRECT3DDEVICE9 d3ddev){
for(DWORD i = 0; i < mNumMaterials; i++)    // loop through each subset
{
	d3ddev->SetMaterial(&mMaterials[i]);    // set the appropriate material for the subset
		if(mTextures[i] != NULL)    // if the subset has a texture (if texture is not NULL)
			d3ddev->SetTexture(0, mTextures[i]);    // ...then set the texture
	mMesh->DrawSubset(i);    // draw the subset
}
	d3ddev->SetTexture(0,NULL);
}

void Mesh::Release(){
	mMesh->Release();
}

LPD3DXMESH Mesh::GetMesh(){
	return mMesh;	
}

D3DMATERIAL9* Mesh::GetMaterials(){
	return mMaterials;
}

DWORD Mesh::GetNumMaterials()
{
	return mNumMaterials;
}

string Mesh::GetName(){
	return mName;
}

string Mesh::GetLocation(){
	return mLocation;
}

void Mesh::GetName(string pName){
	mName = pName;
}

void Mesh::GetLocation(string pLocation){
	mLocation = pLocation;
}